using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{
	
	public partial class FormFieldRules : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		
#region  Web Form Designer Generated Code
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
		}
		
#endregion
		
#region Controls
		protected System.Web.UI.WebControls.Label lblHeading;
		protected System.Web.UI.WebControls.GridView gvFieldRules;
		protected System.Web.UI.WebControls.DropDownList lstSourceField;
		protected TextBox txtContains;
		protected RequiredFieldValidator rfvContains;
		protected LinkButton cmdAddRule;
		protected Label lblChecked;
		protected CheckBoxList chkLstFields;
#endregion
		
#region Private Members
		
		private DotNetNuke.Entities.Modules.PortalModuleBase _loaderCtl;
		private FormSettings objFormSettings;
		private string strOperationSuccess;
		private string strInvalidQuery;
		List<string> targetFields;
		
#endregion
		
#region Event Handlers
		
		private void Page_Load(System.Object sender, System.EventArgs e)
		{
			try
			{
				this.LoaderCtl = (PortalModuleBase) this.Parent.Parent;
				
				strOperationSuccess = Localization.GetString("OperationSuccess", this.LocalResourceFile);
				strInvalidQuery = Localization.GetString("InvalidQuery", this.LocalResourceFile);
				
				objFormSettings = Utility.GetFormSettings(ModuleId);
				
				Utility.LocalizeGridView(this.gvFieldRules, this.LocalResourceFile);
				
				if (!Page.IsPostBack)
				{
					BindData();
				}
			}
			catch (Exception exc)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
			}
		}
		
		protected void lstSourceField_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			
			this.txtContains.Visible = true;
			this.rfvContains.Enabled = true;
			this.lblChecked.Visible = false;
			
			if (this.lstSourceField.SelectedIndex > 0)
			{
				Code5Systems.FormMaster.Business.FormController objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
				Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = objFormCtl.GetFormControlInfo(this.lstSourceField.SelectedValue);
				if (oFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.CheckBox)
				{
					this.txtContains.Visible = false;
					this.rfvContains.Enabled = false;
					this.lblChecked.Visible = true;
				}
			}
			
		}
		
		protected void cmdAddRule_Click(System.Object sender, System.EventArgs e)
		{
			if (Page.IsValid)
			{
				try
				{
					
					Code5Systems.FormMaster.Business.FormFieldRulesController oFieldRulesCtl = new Code5Systems.FormMaster.Business.FormFieldRulesController();
					Code5Systems.FormMaster.Business.FormFieldRulesInfo oFieldRulesInfo = new Code5Systems.FormMaster.Business.FormFieldRulesInfo();
					
					Code5Systems.FormMaster.Business.FormController objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
					Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = objFormCtl.GetFormControlInfo(this.lstSourceField.SelectedValue);
					
					oFieldRulesInfo.FormID = objFormCtl.FormInfo.FormID;
					oFieldRulesInfo.SourceField = this.lstSourceField.SelectedValue;
					oFieldRulesInfo.SourceFieldName = oFormControlInfo.FieldName;
					oFieldRulesInfo.FieldType = System.Convert.ToByte(oFormControlInfo.Type);
					oFieldRulesInfo.ContainsValue = System.Convert.ToString((oFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.CheckBox ? (Localization.GetString("Checked", this.LocalResourceFile)) : this.txtContains.Text).ToString());
					
					string strFields = string.Empty;
					foreach (ListItem item in this.chkLstFields.Items)
					{
						if (item.Selected)
						{
							if (item.Value == oFieldRulesInfo.SourceField)
							{
								throw (new Exception(Localization.GetString("TargetSourceFieldError.Text", this.LocalResourceFile)));
							}
							strFields += item.Value + ",";
							
							Code5Systems.FormMaster.Business.FormControlInfo oParentControl = objFormCtl.GetFormControlInfo(item.Value);
							if (oParentControl.Type == Code5Systems.FormMaster.Business.ControlType.DropDownList)
							{
								while (oParentControl != null && oParentControl.IsParentList)
								{
									strFields += oParentControl.ChildControlID + ",";
									oParentControl = objFormCtl.GetFormControlInfo(oParentControl.ChildControlID);
								}
							}
							
						}
					}
					
					
					strFields = strFields.Substring(0, strFields.Length - 1);
					
					oFieldRulesInfo.FormFields = strFields;
					
					foreach (GridViewRow row in this.gvFieldRules.Rows)
					{
						//Is the Source being used as a Target in another Rule
						if (row.Cells[3].Text.Contains(oFieldRulesInfo.SourceFieldName))
						{
							//Is the Source of the other Rule contained in the Target for this rule
							ListItem item = this.lstSourceField.Items.FindByText(row.Cells[1].Text);
							if (oFieldRulesInfo.FormFields.Contains(item.Value))
							{
								throw (new Exception(Localization.GetString("CirularRuleViolaton.Text", this.LocalResourceFile)));
							}
						}
					}
					
					oFieldRulesCtl.Add(oFieldRulesInfo);
					
					BindData();
				}
				catch (Exception ex)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				}
				
			}
			
			
		}

		protected void gvFieldRules_DataBound(object sender, System.EventArgs e)
		{
			if ((!Request.UserAgent.Contains("MSIE")) || Request.Browser.Platform.Contains("Mac"))
			{
				if (DotNetNuke.Framework.AJAX.IsInstalled())
				{
					Utility.DisableAjax(this);
				}
			}
		}

		protected void gvFieldRules_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
		{
			if (e.CommandName == "Delete")
			{
				int fieldRuleId = Null.NullInteger;
				int.TryParse((e.CommandArgument).ToString(), out fieldRuleId);
				if (fieldRuleId != Null.NullInteger)
				{
					Code5Systems.FormMaster.Business.FormFieldRulesController oFormFieldRuleCtl = new Code5Systems.FormMaster.Business.FormFieldRulesController();
					oFormFieldRuleCtl.Delete(fieldRuleId);
					BindData();
				}
			}
		}

		protected void gvFieldRules_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			LinkButton cmdDeleteRule = (LinkButton) (e.Row.FindControl("cmdDeleteRule"));
			string[] aryFields = null;
			ListItem item = default(ListItem);
			if (cmdDeleteRule != null)
			{
				cmdDeleteRule.Text = Localization.GetString("Delete.CommandText", this.LocalResourceFile);
				cmdDeleteRule.Attributes.Add("onclick", "javascript:return confirm(\'" + Localization.GetString("DeleteItemMessage", LocalResourceFile) + "\');");
				Code5Systems.FormMaster.Business.FormFieldRulesInfo oFormFieldInfo = e.Row.DataItem as Code5Systems.FormMaster.Business.FormFieldRulesInfo;
				if (oFormFieldInfo != null)
				{
					cmdDeleteRule.CommandArgument = (oFormFieldInfo.FieldRuleID).ToString();
				}
			}
			
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				string fields = e.Row.Cells[3].Text;
				if (!string.IsNullOrEmpty(e.Row.Cells[3].Text))
				{
					aryFields = e.Row.Cells[3].Text.Split(',');
					string fieldNames = string.Empty;
					for (int i = 0; i <= aryFields.Length - 1; i++)
					{
						if (targetFields.Contains(aryFields[i]))
						{
							item = this.chkLstFields.Items.FindByValue(aryFields[i]);
							if (item != null)
							{
								
								//**** Replace the Cryptic Control Names with the Field Names and Add a Line Break
								fieldNames += item.Text;
								if (i < aryFields.Length - 1)
								{
									fieldNames += "<br/>";
								}
								
								//***** Disable Target Fields Already In use from the Target List
								//item.Enabled = False
								
								//**** Remove any Target Fields Already In use from the Source Field List *****
								item = this.lstSourceField.Items.FindByValue(aryFields[i]);
								if (item != null)
								{
									//Me.lstSourceField.Items.Remove(item)
								}
							}
						}
					}
					
					e.Row.Cells[3].Text = fieldNames;
					
					//**** Remove any Source Fields Already In use from the Source Field List *****
					string sourceField = e.Row.Cells[1].Text;
					if (!string.IsNullOrEmpty(sourceField))
					{
						item = this.lstSourceField.Items.FindByText(sourceField);
						if (item != null)
						{
							//Me.lstSourceField.Items.Remove(item)
						}
						
						//***** Disable any Field Used as a Source from the Target List
						item = this.chkLstFields.Items.FindByText(sourceField);
						if (item != null)
						{
							//item.Enabled = False
						}
					}
				}
				
			}
			
			
		}

		protected void gvFieldRules_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
		{
			e.Cancel = false;
		}
		
#endregion
		
#region Data Bind Methods
		
		private void BindData()
		{
			
			try
			{
				Code5Systems.FormMaster.Business.FormController objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
				Code5Systems.FormMaster.Business.FormInfo objFormInfo = objFormCtl.FormInfo;
				
				this.lstSourceField.Items.Clear();
				objFormCtl.BindDynamicControls(this.lstSourceField, ModuleId, true);
				this.lstSourceField.Items.Insert(0, new ListItem(Localization.GetString("Select.Text", Utility.GetSharedResourceFile()), "-1"));
				
				this.chkLstFields.Items.Clear();
				objFormCtl.BindDynamicControls(this.chkLstFields, ModuleId, true, false, false, false);
				
				Code5Systems.FormMaster.Business.FormFieldRulesController oFieldRulesCtl = new Code5Systems.FormMaster.Business.FormFieldRulesController();
				
				targetFields = oFieldRulesCtl.GetTargetFields(objFormInfo.FormID);
				
				this.gvFieldRules.DataSource = oFieldRulesCtl.GetByForm(objFormInfo.FormID);
				this.gvFieldRules.DataBind();
				
				this.txtContains.Text = string.Empty;
				
			}
			catch (Exception ex)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
			
			
		}
		
#endregion
		
#region Public Properties
		public PortalModuleBase LoaderCtl
		{
			get
			{
				if (_loaderCtl == null)
				{
					_loaderCtl = this;
				}
				
				return _loaderCtl;
			}
			set
			{
				_loaderCtl = value;
			}
		}
#endregion
		
		
	}
	
}


